package com.dudu.timer;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;

import com.dudu.bean.PushAccountBean;
import com.dudu.dao.PushAccountDao;
import com.dudu.model.PushAccount;
import com.dudu.utils.EnumUtility;
import com.dudu.utils.HttpClientCenter;
import com.dudu.utils.HttpRequest;

import core.CoreDao;
/**
 * 线程把accounts进行处理
 *	1、更新主cust_account的几个URL，把副账号的URL送到主的上。
 *	2、根据副账号对应的app_key得到推送地址，进行推送
 *	3、失败，入库等JOB执行
 *	4、成功，入库留做记录
 * @author gaoxs
 *
 */
public class SendAccountThread implements Runnable {
	private static final Logger log =  core.util.Logger.getLogger(SendAccountThread.class.getSimpleName());
	private PushAccountDao accountDao=null;
	private PushAccountBean bean=null;
	private CoreDao dao = null;
	public SendAccountThread(CoreDao dao,PushAccountBean bean,PushAccountDao accountDao){
		this.accountDao=accountDao;
		this.bean=bean;
		this.dao=dao;
	}
	@Override
	public void run() {
		JSONObject data=new JSONObject();
		data.put("describe", "账号信息");
		JSONObject object=new JSONObject();
		object.put("cust_account_vice", bean.getVice_cust_account());
		object.put("cust_account", bean.getCust_account());
		object.put("org_tempKey", bean.getKey_private());
		object.put("org_permKey", bean.getKey_public());
		data.put("data", object);
		log.info("SendAccountThread===URL"+bean.getRecord_url()+"----参数:"+data.toString());
		String response = null;//响应
		if(EnumUtility.isNotBlank(bean.getRecord_url())){//推送地址不能为空
			if(bean.getRecord_url().startsWith("https")){
				//推送地址为https
				HttpClientCenter httpClientCenter = new HttpClientCenter(bean.getRecord_url());
				response = httpClientCenter.postHttps(data.toString(), "application/json");
			}else if(bean.getRecord_url().startsWith("http")){
				//推送地址为http
				response = HttpRequest.postData(bean.getRecord_url(), data.toString());
			}else{
				log.info("推送地址非法："+bean.getRecord_url());
			}
		
		}else{
			log.info("推送数据因URL为空则不进行推送"+"resp:"+data.toString());
		}
		log.info("SendAccountThread======"+response);
		if(EnumUtility.isNotBlank(response)){
			JSONObject retJson = JSONObject.fromObject(response);
			String desc = retJson.optString("describe");//响应描述
			String code = retJson.optString("result");
			
			if(EnumUtility.isNotBlank(code) &&  code.equals("0") ){
				log.info("更新发送成功的记录信息");
				updateCode(bean);//更新
				
			}
		}
	}
	private void updateCode(PushAccountBean bean){
		PushAccount account=new PushAccount();
		BeanUtils.copyProperties(bean,account);//源,目的
		account.setCode("0");//设置已发送
		accountDao.update(dao, account);
	}

}
